package VideoProcessing;

import java.awt.image.WritableRaster;

import javax.media.format.VideoFormat;

public class Diffeffect extends RgbVideoEffect {
	private static final byte NONE = (byte) 255;
	private static final int THRESHOLD = 4;
	BufferAccessor firstPre, secondPre;

	public Diffeffect(BufferAccessor firstPre, BufferAccessor secondPre) {
		this.firstPre = firstPre;
		this.secondPre = secondPre;
	}

	@Override
	protected boolean processRGB(byte[] bin, byte[] bout, VideoFormat format) {
		if (firstPre.getBuffer() == null || secondPre.getBuffer() == null) {
			return false;
		}
		byte[] current, pre1, pre2;
		int[] diff1, diff2;
		current = bin;
		pre1 = firstPre.getBuffer();
		pre2 = secondPre.getBuffer();
		diff1 = getDifference(pre2, pre1);
		diff2 = getDifference(pre1, current);
		diff1 = threshold(diff1);
		diff2 = threshold(diff2);
		for (int i = 0; i < diff1.length; i++) {
			bout[i] = (byte) ((diff1[i] == 1 && diff2[i] == 1) ? 1 : 0);
		}
		return true;
	}

	private int[] threshold(int[] array) {
		for (int i = 0; i < array.length; i++) {
			if (array[i] > THRESHOLD) {
				array[i] = 1;
			} else {
				array[i] = 0;
			}
		}
		return array;
	}

	private int[] getDifference(byte[] pre1, byte[] current) {
		int[] diff = new int[pre1.length];
		for (int i = 0; i < diff.length; i++) {
			diff[i] = Math.abs(byte2Int(pre1[i]) - byte2Int(current[i]));
		}
		return diff;
	}

	@Override
	public String getName() {
		return "Difference Effect";
	}
	protected void updateImage(byte[] bout, VideoFormat vformat) {
		synchronized (displayImage) {
			// // Copy pixels to image
			WritableRaster rast = displayImage.getRaster();
			int[] pixel = new int[] { 0, 0, 0, 255 };
			int p = 0;
			for (int y = vformat.getSize().height - 1; y >= 0; y--) {
				for (int x = 0; x < vformat.getSize().width; x++) {
					pixel[0] = pixel[1] = pixel[2] = bout[p++];
					rast.setPixel(x, y, pixel);
				}
			}
		}
	}
}
